package siau.android.base

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import hhm.android.library.bus.Bus
import hhm.android.library.utils.OnMultiClickListener
import siau.android.base.SBApplication.Companion.communityChildId
import siau.android.base.SBApplication.Companion.mainPageChange
import siau.android.base.SBApplication.Companion.userData
import siau.android.base.enum.HeightClass
import siau.android.base.enum.WeightClass
import siau.android.http.model.ChildModel
import siau.android.http.model.RecordHeightDataRequest
import siau.android.http.model.RecordWeightDataRequest
import siau.android.library.KeyString
import java.util.*
import kotlin.collections.ArrayList

class GetBlueToothDataActivity : AppCompatActivity() {

    /**
     *  val i = Intent(context, GetBlueToothDataActivity::class.java)
     *   i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
     *   context.startActivity(i)
     */

    lateinit var adapter: BottomSingleBabySelectAdapter
    var list = ArrayList<ChildModel>()
    var type = -1 //1体重 2身高 3鞋码
    var cla = -1 //0 kg ,  1 cm , 2 ft , 3 斤 , 4 lb
    var childId = -1
    var data: Double = 0.0
    var resultData = 0.0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_get_blue_tooth_data)

        Bus.getDefault().register(this)

        type = intent.getIntExtra(KeyString.type, -1)
        data = intent.getDoubleExtra(KeyString.data, 0.0)
        cla = intent.getIntExtra(KeyString.cla, -1)

        userData.children?.forEach {
            if (it.childId == -1 && it.familyId == -1 && it.nickName == "") {
            } else {
                val n = ChildModel(
                    it.childId, it.nickName, if (it.avatar.isNullOrEmpty()) {
                        ""
                    } else {
                        it.avatar
                    }, it.select, it.familyId, it.birthday, it.sex, if (it.height.isNaN()) {
                        -1.0
                    } else {
                        it.height
                    }, if (it.weight.isNaN()) {
                        -1.0
                    } else {
                        it.weight
                    }
                )
                if (n.select) {
                    childId = n.childId
                    when (type) {
                        1 -> {
                            if (!TextUtils.isEmpty(n.weight.toString())) {
                                resultData = n.weight
                            }
                        }
                        2 -> {
                            if (!TextUtils.isEmpty(n.height.toString())) {
                                resultData = n.height
                            }
                        }
                    }
                }
                list.add(n)
            }
        }

        Log.d("hhm-->id", "childId:$childId")

        val tv: TextView = findViewById(R.id.activity_get_blue_tooth_data_tv)
        val recycler: RecyclerView = findViewById(R.id.activity_get_blue_tooth_data_recycler)
        val sure: TextView = findViewById(R.id.activity_get_blue_tooth_data_sure)
        val cancel: TextView = findViewById(R.id.activity_get_blue_tooth_data_cancel)
        val addBaby: TextView = findViewById(R.id.activity_get_blue_tooth_data_add)
        val tip: TextView = findViewById(R.id.activity_get_blue_tooth_data_tip)
        if (userData.isCreator != 1) {
            addBaby.visibility = View.GONE
        }

        var clazz = ""
        var updateCLass = ""
        when (cla) {//0 kg ,  1 cm , 2 ft , 3 斤 , 4 lb
            0 -> {
                clazz = getString(R.string.class_kg)
                updateCLass = WeightClass.KG.msg
                tip.text = getString(R.string.we_get_calculate_data_w)
            }
            1 -> {
                clazz = getString(R.string.class_cm)
                updateCLass = HeightClass.CM.msg
                tip.text = getString(R.string.we_get_calculate_data_h)
            }
            2 -> {
                clazz = getString(R.string.class_ft)
                updateCLass = HeightClass.FT.msg
                tip.text = getString(R.string.we_get_calculate_data_h)
            }
            3 -> {
                clazz = getString(R.string.class_jin)
                updateCLass = WeightClass.JIN.msg
                tip.text = getString(R.string.we_get_calculate_data_w)
            }
            4 -> {
                clazz = getString(R.string.class_bang)
                updateCLass = WeightClass.LB.msg
                tip.text = getString(R.string.we_get_calculate_data_w)
            }
        }
        tv.text = if (clazz == getString(R.string.class_ft)) {
            val tmpFoot = (data * 100 / 3048).toInt()
            val tmpInchDecade = ((data * 100 % 3048 / 254.0 * 10 + 5) / 100).toInt()
            val tmpInchUnit = ((data * 100 % 3048 / 254.0 * 10 + 5) % 100 / 10).toInt()
            val heightS: String = if (tmpInchDecade == 1 && tmpInchUnit == 2) {
                "" + (tmpFoot + 1)
            } else {
                if (tmpInchDecade == 0) {
                    if (tmpInchUnit == 0) {
                        "" + tmpFoot
                    } else {
                        "$tmpFoot.$tmpInchUnit"
                    }
                } else {
                    "$tmpFoot.$tmpInchDecade$tmpInchUnit"
                }
            }
            if (heightS.contains(".")) {
                val split = heightS.split(".")
                if (split[1].toInt() == 0) {
                    split[0] + "ft"
                } else {
                    split[0] + "ft" + split[1] + "in"
                }
                if (split[0].toInt() == 0) {
                    split[1] + "in"
                } else {
                    split[0] + "ft" + split[1] + "in"
                }
            } else {
                heightS + "ft"
            }
        } else if (clazz == getString(R.string.class_cm)) {
            "%.1f".format(data) + clazz
        } else if (clazz == getString(R.string.class_bang)) {
            val lbWeight = data * 2.2046
            "%.1f".format(lbWeight) + clazz
        } else {
            data.toString() + clazz
        }

        recycler.layoutManager = LinearLayoutManager(this)
        recycler.isNestedScrollingEnabled = false

        adapter = BottomSingleBabySelectAdapter(this, list, 1/*目前写死不是3就行*/, object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                val pos = v?.tag as Int
                list.forEach {
                    it.select = false
                }
                list[pos].select = true
                childId = list[pos].childId
                when (type) {
                    1 -> {
                        if (!TextUtils.isEmpty(list[pos].weight.toString())) {
                            resultData = list[pos].weight
                        }
                    }
                    2 -> {
                        if (!TextUtils.isEmpty(list[pos].height.toString())) {
                            resultData = list[pos].height
                        }
                    }
                }
                adapter.notifyDataSetChanged()
            }
        })
        recycler.adapter = adapter

        cancel.setOnClickListener(object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                finish()
            }
        })
        sure.setOnClickListener(object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                when (type) {
                    1 -> {
                        when (userData.weightUnit) {
                            WeightClass.KG.msg -> {
                                SBApplication.getBlueToothUtils().sendResultToWeightMachine(null, resultData, data)
                            }
                            WeightClass.JIN.msg -> {
                                SBApplication.getBlueToothUtils().sendResultToWeightMachine(null, resultData / 2, data)
                            }
                            else -> {
                                SBApplication.getBlueToothUtils().sendResultToWeightMachine(null, resultData / 2.2, data)
                            }
                        }
                        val r = RecordWeightDataRequest(childId, Date().time, 1, data.toString(), weightUnit = WeightClass.KG.msg)

                        HttpHelper().recordWeight(r)?.subscribe({
                            for (cm in userData.children!!) {
                                if (cm.childId == childId) {
                                    val cmData = if (userData.weightUnit == WeightClass.LB.msg) {
                                        val lbWeight = data / 2.2046
                                        "%.1f".format(lbWeight).toDouble()
                                    } else {
                                        data
                                    }
                                    cm.weight = cmData
                                }
                            }
                            val mpcd = MainPageChangeData()
                            mpcd.deviceType = 1
                            mpcd.childId = childId
                            communityChildId = r.childId
                            userData.children!!.forEach { i ->
                                i.select = i.childId == childId
                            }
                            mainPageChange.value = mpcd
                            finish()
                        }, {
                            Toast.makeText(this@GetBlueToothDataActivity, it.message, Toast.LENGTH_SHORT).show()
                            finish()
                        })
                    }
                    2 -> {
                        if (userData.heightUnit == HeightClass.CM.msg) {
                            SBApplication.getBlueToothUtils().sendResultToHeightMachine(null, resultData, data)
                        } else {
                            if (resultData.toString().contains(".")) {
                                val split = resultData.toString().split(".")
                                SBApplication.getBlueToothUtils().sendResultToHeightMachine(null, split[0].toDouble() * 30.48 + split[1].toDouble() * 2.54, data)
                            } else {
                                SBApplication.getBlueToothUtils().sendResultToHeightMachine(null, resultData * 30.48, data)
                            }
                        }
                        val r = if (cla == 2) {
                            RecordHeightDataRequest(childId, Date().time, 1, data.toString(), heightUnit = HeightClass.CM.msg)
                        } else {
                            RecordHeightDataRequest(childId, Date().time, 1, data.toString(), heightUnit = updateCLass)
                        }

                        HttpHelper().recordHeight(r)?.subscribe({
                            for (cm in userData.children!!) {
                                if (cm.childId == childId) {
                                    if (cla == 2) {
                                        val tmpFoot = (data * 100 / 3048).toInt()
                                        val tmpInchDecade = ((data * 100 % 3048 / 254.0 * 10 + 5) / 100).toInt()
                                        val tmpInchUnit = ((data * 100 % 3048 / 254.0 * 10 + 5) % 100 / 10).toInt()
                                        var heightS: String = if (tmpInchDecade == 0) {
                                            if (tmpInchUnit == 0) {
                                                "" + tmpFoot
                                            } else {
                                                "$tmpFoot.$tmpInchUnit"
                                            }
                                        } else {
                                            if (tmpInchUnit == 0) {
                                                "$tmpFoot.$tmpInchDecade"
                                            } else {
                                                "$tmpFoot.$tmpInchDecade$tmpInchUnit"
                                            }
                                        }
                                        cm.height = heightS.toDouble()
                                    } else {
                                        cm.height = data
                                    }
                                }
                            }
                            val mpcd = MainPageChangeData()
                            mpcd.deviceType = 2
                            mpcd.childId = childId
                            communityChildId = r.childId
                            userData.children!!.forEach { i ->
                                i.select = i.childId == childId
                            }
                            mainPageChange.value = mpcd
                            finish()
                        }, {
                            Toast.makeText(this@GetBlueToothDataActivity, it.message, Toast.LENGTH_SHORT).show()
                            finish()
                        })
                    }
                    3 -> {
                        finish()
                    }
                }
            }
        })
        addBaby.setOnClickListener(object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                ARouter.getInstance().build(BABY_ROUTE).withInt(KeyString.type, 0).navigation()
                finish()
            }
        })
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
    }

    override fun finish() {
        super.finish()
        Bus.getDefault().unregister(this)
    }
}